import React, { useState, useEffect } from 'react';
import { Container, Table, Button, Alert, Modal, Form } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';
import UserService from '../services/UserService';
import AuthService from '../services/AuthService';

const AdminDashboard = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [editForm, setEditForm] = useState({
    email: '',
    fullName: '',
    enabled: true
  });
  
  const navigate = useNavigate();

  useEffect(() => {
    // 验证是否为管理员
    const user = AuthService.getCurrentUser();
    console.log('AdminDashboard - 当前用户:', user);
    
    // 检查角色是直接在user对象上还是在user.user中
    let isAdmin = false;
    if (user) {
      if (user.role === 'ROLE_ADMIN') {
        isAdmin = true;
      } else if (user.user && user.user.role === 'ROLE_ADMIN') {
        isAdmin = true;
      }
    }
    
    if (!isAdmin) {
      console.log('不是管理员，重定向到登录页');
      navigate('/login');
      return;
    }
    
    // 加载用户列表
    loadUsers();
  }, [navigate]);

  const loadUsers = () => {
    setLoading(true);
    console.log('开始加载用户列表');
    UserService.getAllUsers()
      .then(response => {
        console.log('获取用户列表响应:', response);
        if (response.data && response.data.data) {
          setUsers(response.data.data);
        }
        setLoading(false);
      })
      .catch(error => {
        console.error('获取用户列表错误:', error.response || error);
        setError('获取用户列表失败: ' + (error.response?.data?.message || error.message || '未知错误'));
        setLoading(false);
      });
  };

  const handleDeleteClick = (user) => {
    setCurrentUser(user);
    setShowDeleteModal(true);
  };

  const handleEditClick = (user) => {
    setCurrentUser(user);
    setEditForm({
      email: user.email || '',
      fullName: user.fullName || '',
      enabled: user.enabled
    });
    setShowEditModal(true);
  };

  const handleDelete = () => {
    if (!currentUser) return;
    
    UserService.deleteUser(currentUser.id)
      .then(() => {
        setShowDeleteModal(false);
        loadUsers();
      })
      .catch(error => {
        setError('删除用户失败');
        console.error('Error deleting user:', error);
      });
  };

  const handleEditFormChange = (e) => {
    const { name, value, checked } = e.target;
    setEditForm({
      ...editForm,
      [name]: name === 'enabled' ? checked : value
    });
  };

  const handleEdit = () => {
    if (!currentUser) return;
    
    const updatedUser = {
      ...currentUser,
      ...editForm
    };
    
    UserService.updateUser(currentUser.id, updatedUser)
      .then(() => {
        setShowEditModal(false);
        loadUsers();
      })
      .catch(error => {
        setError('更新用户失败');
        console.error('Error updating user:', error);
      });
  };

  return (
    <Container className="mt-4">
      <h2 className="mb-4">管理员控制面板</h2>
      
      {error && <Alert variant="danger">{error}</Alert>}
      
      {loading ? (
        <p>加载中...</p>
      ) : (
        <Table striped bordered hover responsive>
          <thead>
            <tr>
              <th>ID</th>
              <th>用户名</th>
              <th>电子邮箱</th>
              <th>姓名</th>
              <th>角色</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {users.map(user => (
              <tr key={user.id}>
                <td>{user.id}</td>
                <td>{user.username}</td>
                <td>{user.email}</td>
                <td>{user.fullName}</td>
                <td>{user.role}</td>
                <td>{user.enabled ? '激活' : '禁用'}</td>
                <td>
                  <Button 
                    variant="primary" 
                    size="sm" 
                    className="me-2"
                    onClick={() => handleEditClick(user)}
                  >
                    编辑
                  </Button>
                  {user.role !== 'ROLE_ADMIN' && (
                    <Button 
                      variant="danger" 
                      size="sm"
                      onClick={() => handleDeleteClick(user)}
                    >
                      删除
                    </Button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </Table>
      )}

      {/* 删除确认对话框 */}
      <Modal show={showDeleteModal} onHide={() => setShowDeleteModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>确认删除</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          您确定要删除用户 "{currentUser?.username}" 吗？此操作不可撤销。
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowDeleteModal(false)}>
            取消
          </Button>
          <Button variant="danger" onClick={handleDelete}>
            删除
          </Button>
        </Modal.Footer>
      </Modal>

      {/* 编辑用户对话框 */}
      <Modal show={showEditModal} onHide={() => setShowEditModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>编辑用户</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form>
            <Form.Group className="mb-3">
              <Form.Label>用户名</Form.Label>
              <Form.Control
                type="text"
                value={currentUser?.username || ''}
                disabled
              />
            </Form.Group>
            
            <Form.Group className="mb-3">
              <Form.Label>电子邮箱</Form.Label>
              <Form.Control
                type="email"
                name="email"
                value={editForm.email}
                onChange={handleEditFormChange}
              />
            </Form.Group>
            
            <Form.Group className="mb-3">
              <Form.Label>姓名</Form.Label>
              <Form.Control
                type="text"
                name="fullName"
                value={editForm.fullName}
                onChange={handleEditFormChange}
              />
            </Form.Group>
            
            <Form.Group className="mb-3">
              <Form.Check
                type="checkbox"
                label="账户启用"
                name="enabled"
                checked={editForm.enabled}
                onChange={handleEditFormChange}
              />
            </Form.Group>
          </Form>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => setShowEditModal(false)}>
            取消
          </Button>
          <Button variant="primary" onClick={handleEdit}>
            保存
          </Button>
        </Modal.Footer>
      </Modal>
    </Container>
  );
};

export default AdminDashboard; 